package com.dchh.android.suverynew.act;

import android.app.Dialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.dchh.android.suverynew.R;
import com.dchh.android.suverynew.base.SBaseActivity;
import com.dchh.android.suverynew.common.SPreferencesManager;
import com.dhcc.android.base.base.MSApplication;
import com.dhcc.android.base.common.bean.KeyValueBean;
import com.dhcc.android.base.common.view.AutoCompleteTextView.InitAutoCompleteUtil;
import com.dhcc.android.base.common.view.AutoCompleteTextView.MyAutoCompleteTextView;
import com.dhcc.android.base.common.view.ListViewPoupWindow;
import com.dhcc.android.base.common.view.MyLoadingDialog;
import com.dhcc.android.base.utils.CommenUtil;
import com.dhcc.android.base.utils.Constants;
import com.dhcc.android.base.utils.StringUtil;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;

/**
 * 网络配置
 *
 * @author pengling
 * @date 2014年8月29日
 */
public class NetConfigActivity extends SBaseActivity {
    /**
     * 标题控件
     */
    private TextView title;
    /**
     * logo
     */
    private ImageView logo;
    /**
     * AutoCompleteTextView
     */
    private MyAutoCompleteTextView ip;
    private MyAutoCompleteTextView portNum;
    /**
     * 测试按钮
     */
    private Button testLinkSrcBtn;
    /**
     * 确定按钮
     */
    private Button confrimLinkSrcBtn;

    /**
     * IP弹窗
     */
    private Dialog dialog;
    private int checkFlag = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setToolBarShow(false);
        setContentView(R.layout.main_netconfig);
    }

    @Override
    protected void setTitle(TextView toolbar_title) {

    }

    @Override
    protected void initView() {
        dialog = MyLoadingDialog.createLoadingDialog(NetConfigActivity.this,
                this.getString(R.string.common_dialog_connecting));
        // 设置标题样式
        title = (TextView) findViewById(R.id.title);
        RelativeLayout.LayoutParams layoutParam = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT);
        layoutParam.setMargins(0, Constants.screenHight / 10, 0, 0);
        layoutParam.addRule(RelativeLayout.CENTER_HORIZONTAL);
        title.setLayoutParams(layoutParam);

        logo = (ImageView) findViewById(R.id.logo);
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                Constants.screenHight / 6, Constants.screenHight / 6);
        lp.setMargins(0, 10, 0, 0);
        lp.addRule(RelativeLayout.CENTER_HORIZONTAL);
        lp.addRule(RelativeLayout.BELOW, R.id.title);
        logo.setLayoutParams(lp);

        // 设置 ip、端口号输入框样式
        ip = (MyAutoCompleteTextView) findViewById(R.id.ip);
        portNum = (MyAutoCompleteTextView) findViewById(R.id.portnum);

        layoutParam = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.FILL_PARENT,
                Constants.screenHight / 12);
        ip.setLayoutParams(layoutParam);
        CommenUtil.setAutoTextStyle(ip,
                this.getString(R.string.netConfigActivity_ip),
                EditorInfo.TYPE_CLASS_PHONE, EditorInfo.IME_ACTION_NEXT,
                R.mipmap.user);
        CommenUtil.setAutoTextStyle(portNum,
                this.getString(R.string.netConfigActivity_port),
                EditorInfo.TYPE_CLASS_PHONE, EditorInfo.IME_ACTION_DONE,
                R.mipmap.lock);
        // 初始网络配置历史ip
        InitAutoCompleteUtil.initAutoComplete(this, MSApplication.IP_HISTORY,
                ip);
        // 初始网络配置历史port
        InitAutoCompleteUtil.initAutoComplete(this, MSApplication.PORT_HISTORY,
                portNum);

        // 注册监听
        testLinkSrcBtn = (Button) findViewById(R.id.testlinksrcbutton);
        confrimLinkSrcBtn = (Button) findViewById(R.id.confirmlinksrcbutton);

        testLinkSrcBtn.setOnClickListener(itemOnClick);
        confrimLinkSrcBtn.setOnClickListener(itemOnClick);
        findViewById(R.id.configbtn).setOnClickListener(itemOnClick);

        ip.setOnEditorActionListener(new EditText.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId,
                                          KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_NEXT
                        || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    portNum.requestFocus();
                    portNum.setFocusable(true);
                    return true;
                }
                return false;
            }
        });

        portNum.setOnEditorActionListener(new EditText.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId,
                                          KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    InputMethodManager imm = (InputMethodManager) v
                            .getContext().getSystemService(
                                    Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                    checkFlag = 2;
                    TestLinkSrc();
                    return true;
                }
                return false;
            }
        });
    }

    /**
     * 测试地址是否可以连接
     */
    private void TestLinkSrc() {
        if (ip.getText().equals("")) {
            Toast.makeText(this,
                    this.getString(R.string.netConfigActivity_ip_no),
                    Toast.LENGTH_LONG).show();
        } else if (portNum.getText().equals("")) {
            // InitAutoCompleteUtil.saveHistory(NetConfigActivity.this,
            // MSApplication.IP_HISTORY, ip.getText().toString());
            Toast.makeText(this,
                    this.getString(R.string.netConfigActivity_port_no),
                    Toast.LENGTH_LONG).show();
        } else if (!StringUtil.isboolIP(ip.getText() + ":" + portNum.getText())) {

            Toast.makeText(this,
                    this.getString(R.string.netConfigActivity_port_error),
                    Toast.LENGTH_LONG).show();
        } else {
            InitAutoCompleteUtil.saveHistory(NetConfigActivity.this,
                    MSApplication.IP_HISTORY, ip.getText().toString());
            InitAutoCompleteUtil.saveHistory(NetConfigActivity.this,
                    MSApplication.PORT_HISTORY, portNum.getText().toString());
            dialog.show();
            new Thread(netConnect).start();
        }
    }

    Runnable netConnect = new Runnable() {

        private void sendMsg(int what) {
            Message msg = new Message();
            msg.what = what;
            netHanlder.sendMessage(msg);
        }

        @Override
        public void run() {
            HttpClient client = new DefaultHttpClient();
            HttpPost request;
            try {
                String url = "http://" + ip.getText() + ":" + portNum.getText()
                        + Constants.loginUrl;
                System.out.println("###访问路径：" + url);
                request = new HttpPost(new URI(url));

                HttpResponse response = client.execute(request);
                if (response.getStatusLine().getStatusCode() == 200) {
                    System.out.println("###连接成功");
                    sendMsg(0);
                } else {
                    System.out.println("###连接失败");
                    sendMsg(1);
                }

            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("###连接出错");
                sendMsg(1);
            }
        }
    };

    Handler netHanlder = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            dialog.dismiss();
            switch (msg.what) {
                case 0:
                    Toast.makeText(NetConfigActivity.this, "测试连接成功",
                            Toast.LENGTH_SHORT).show();
                    if (checkFlag == 2) {
                        confirmLinkSrc();
                    }
                    break;
                case 1:
                    Toast.makeText(NetConfigActivity.this, "测试连接失败",
                            Toast.LENGTH_SHORT).show();

                    break;

                default:
                    break;
            }
        }

    };

    /**
     * 展现固定IP
     */
    private void showIpListPoup(View v) {
        final ListViewPoupWindow listViewPoupWindow = new ListViewPoupWindow(
                this, "请选择相应地址：");
        final List<KeyValueBean> keyValueList = getConfigDatas();
        if (keyValueList == null || keyValueList.size() == 0) {
            CommenUtil.toast("没有可选地址，请先填写", this);
        } else {
            listViewPoupWindow.initPopWindow(v, keyValueList, true);
            listViewPoupWindow.listView
                    .setOnItemClickListener(new OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> arg0, View arg1,
                                                int arg2, long arg3) {
                            if (StringUtil.isFastDoubleClick(500)) {
                                return;
                            }

                            KeyValueBean keyValue = keyValueList.get(arg2);
                            String value = keyValue.getValue();
                            listViewPoupWindow.dismiss();
                            ip.setText(value.split(":")[0]);
                            ip.setSelection(value.split(":")[0].length());
                            portNum.setText(value.split(":")[1]);
                            portNum.setSelection(value.split(":")[1].length());
                        }
                    });
        }
    }

    /**
     * 得到可选地址
     */
    private List<KeyValueBean> getConfigDatas() {
        List<KeyValueBean> keyValueList = new ArrayList<KeyValueBean>();
        SharedPreferences sp = this.getSharedPreferences("network_url", 0);
        String longHistory = sp.getString(MSApplication.CONFIG_HISTORY, "");
        if (StringUtil.isEmpty(longHistory)) {
            String Config_Address[] = Constants.Config_Address;
            for (String config : Config_Address) {
                InitAutoCompleteUtil.saveHistory(NetConfigActivity.this,
                        MSApplication.CONFIG_HISTORY, config);
            }
        }
        longHistory = sp.getString(MSApplication.CONFIG_HISTORY, "");
        if (longHistory.equals(",nothing") || longHistory.equals("nothing,")) {// 没数据
            keyValueList = null;
        } else {
            String[] hisArrays = longHistory.split(",");
            for (String config : hisArrays) {
                if (!config.equals("nothing")) {
                    keyValueList.add(new KeyValueBean("", config));
                }
            }
        }

        return keyValueList;

    }

    /**
     * 确认选择的地址
     */
    private void confirmLinkSrc() {
        SPreferencesManager.saveValue(MSApplication.CURRENT_IP, ip.getText());
        SPreferencesManager.saveValue(MSApplication.CURRENT_PORT, portNum.getText());
        Constants.host = ip.getText();
        Constants.port = portNum.getText();
        finish();
    }

    @Override
    protected void onDestroy() {
        new MSApplication().deleteActivity(this);
        super.onDestroy();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            this.finish();
            overridePendingTransition(R.anim.push_right_in,
                    R.anim.push_left_out);
        }
        return true;
    }

    private OnClickListener itemOnClick = new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (StringUtil.isFastDoubleClick(500)) {
                return;
            }
            if (v.getId() == R.id.testlinksrcbutton) {// 测试
                checkFlag = 1;
                TestLinkSrc();
            } else if (v.getId() == R.id.confirmlinksrcbutton) {// 确定
                checkFlag = 2;
                TestLinkSrc();
            } else if (v.getId() == R.id.configbtn) {// 选择地址
                checkFlag = 3;
                showIpListPoup(v);

            }
        }
    };
}
